package netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyByteBuffer {

    /**
     * 注意 netty的byteBuffer 和 java NIO 的byteBuffer 不太一样
     */
    @Test
    public void testByteBuf(){
        // buf 实际类型 UnpooledByteBufAllocator
        ByteBuf buf = Unpooled.buffer(10);
        // 写内容 writerIndex 在增加。此属性没找到在哪里
        for (int i = 0; i < 10; i++) {
            buf.writeByte(i);
        }

        // readerIndex 在增加。此属性没找到在哪里
        for (int i = 0; i < buf.capacity(); i++) {
            System.out.println(buf.readByte());
        }
    }
    
    @Test
    public void nettyByteBufCase2(){
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,word", StandardCharsets.UTF_8);
        
        if (byteBuf.hasArray()){
            byte[] bytes = byteBuf.array();
            log.error(new String(bytes,StandardCharsets.UTF_8).trim());
        }
    }
}
